﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Common.Utility;
using Runda.CMS.Common.Entity;
using Runda.CMS.Bll;
using Runda.CMS.Common.Exchange;

namespace Runda.CMS.Portal.Workspace
{
    public partial class ContractAssign :BasePage
    {
        public Guid ContractID
        {
            get
            {
                if (Request.QueryString["ContractID"] == null) return Guid.Empty;
                else return new Guid(Request.QueryString["ContractID"]);
            } 
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["TrackID"] != null && ContractID != Guid.Empty)
                {
                    txtTrackID.Value = Request.QueryString["TrackID"];

                    WflInstanceRoutingEntity TrackEntity = new WflInstanceRoutingBll().Get<WflInstanceRoutingEntity>(new Guid(Request.QueryString["TrackID"]));
                    if (TrackEntity == null)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "success", "alert('获取数据失败,请联系管理员');window.close();", true);
                    }
                    else
                    {
                        txtActivityID.Value = TrackEntity.ActivityID.ToString();
                        txtInstanceID.Value = TrackEntity.InstanceID.ToString();
                        QueryUsers();
                    }

                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "success", "alert('获取数据失败,请联系管理员');window.close();", true);                
                }
            }
        }

        private void QueryUsers()
        {
            QueryUsers(string.Empty);
        }

        private void QueryUsers(string OrderBy)
        {
            List<WflCommentEntity> list = null;
            WflCommentBll bll = new WflCommentBll();
            if(OrderBy != string.Empty)
                list = bll.GetAll<WflCommentEntity>(" and TrackID = '" + txtTrackID.Value + "'", OrderBy);
            else
                list = bll.GetAll<WflCommentEntity>(" and TrackID = '" + txtTrackID.Value + "'");

            gridUsers.DataSource = list;
            gridUsers.DataBind();
        }

        public string GetStatusText(int status)
        {
            string text = string.Empty;
            EnumeratorHelper[] cs = EnumeratorHelper.GetFieldTexts(typeof(Enumerator.ContractCommentStatus));
            foreach (EnumeratorHelper c in cs)
            {
                if (c.EnumValue == status)
                {
                    text = c.EnumDisplayText; break;
                }
            }

            return text;
        }

        protected void btnRefreshUsers_Click(object sender, EventArgs e)
        {
            QueryUsers();
        }

        protected void gridUsers_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = " Order by " + e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            QueryUsers(OrderBy);
        }

        protected void gridUsers_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.CommandName == "submit")
            {
                Guid CommentID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["CommentID"].ToString());
                CtrtContractEntity entity = new CtrtContractEntity();
                CtrtContractBll bll = new CtrtContractBll();
                entity = bll.Get<CtrtContractEntity>(ContractID);

                WflInstanceBll InstanceBll = new WflInstanceBll();
                WflInstanceEntity InstanceEntity = InstanceBll.Get<WflInstanceEntity>(entity.InstanceID);
                if (InstanceEntity == null) return;

                SysUserEntity userEnty = new SysUserBll().Get<SysUserEntity>(InstanceEntity.CreatedBy);

                WflInstanceRoutingEntity TrackEntity = new WflInstanceRoutingBll().Get<WflInstanceRoutingEntity>(new Guid(Request.QueryString["TrackID"]));

                //添加一条Task 
                WflTaskBll TaskBll = new WflTaskBll();
                WflTaskEntity taskEntity = new WflTaskEntity();
                taskEntity.TaskID = Guid.NewGuid();
                taskEntity.Title = "您有从[" + userEnty .UserName+ "]提交的[合同编号为" + entity.ContractCode + "]阶段工作待完成。";
                taskEntity.Entry = String.Concat("ContractComment.aspx", "?", "TrackID=", TrackEntity.TrackID, "&TaskID=", taskEntity.TaskID, "&BussinessID=", ContractID, "&CommentID=", CommentID);
                taskEntity.ActivityID = TrackEntity.ActivityID;
                taskEntity.Status = 0;
                taskEntity.TaskType = 1;
                TaskBll.Insert(taskEntity);


                WflCommentBll CommentBll = new WflCommentBll();
                WflCommentEntity commentEntity = CommentBll.Get<WflCommentEntity>(CommentID);
                if (commentEntity != null)
                {
                    //commentEntity.CreatedAt = DateTime.Now;
                    //commentEntity.InstanceID = entity.InstanceID;
                    //commentEntity.ActivityID = TrackEntity.ActivityID;
                    //commentEntity.Comments = string.Empty;
                    //commentEntity.LeaderID = Guid.Empty;// new Guid(ddlLeader.SelectedValue);
                    commentEntity.CommentStatus = (byte)Enumerator.ContractCommentStatus.Wait;
                    CommentBll.InsertOrUpdate(commentEntity);

                    //审批人
                    WflTaskUserBll tuBll = new WflTaskUserBll();
                    WflTaskUserEntity tuEntity = new WflTaskUserEntity();
                    tuEntity.ID = Guid.NewGuid();
                    tuEntity.TaskID = taskEntity.TaskID;
                    tuEntity.UserID = commentEntity.LeaderID;
                    tuEntity.CreatedAt = DateTime.Now;
                    tuBll.Insert(tuEntity);

                    //邮件
                    SysUserEntity userEntity = new SysUserBll().Get<SysUserEntity>(commentEntity.LeaderID);
                    MailHandle.SendEmailNotice(base.CurrentUserEntity.UserName, userEntity.Email, "您有一份合同需要填写意见，合同编号：" + entity.ContractCode + "");
                }
                QueryUsers();
            }
        }

        protected void gridUsers_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {
            if (e.Item.ItemType == Telerik.WebControls.GridItemType.Item || e.Item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
            {
                WflCommentEntity entity = e.Item.DataItem as WflCommentEntity;
                if (entity != null)
                {
                    LinkButton lnkbtnSubmit = e.Item.FindControl("lnkbtnSubmit") as LinkButton;
                    if (lnkbtnSubmit != null)
                    {
                        if (entity.CommentStatus != (byte)Enumerator.ContractCommentStatus.Assign)
                        {
                            lnkbtnSubmit.Visible = false;
                        }
                    }
                }
            }
        }
    }
}
